package com.websocket.java.websocket.config;

import com.websocket.java.websocket.handler.CustomTextWebSocketHandler;
import com.websocket.java.websocket.handler.CustomWebSocketHandler;
import com.websocket.java.websocket.interceptor.CustomWebSocketInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @description: 通过重写registerWebSocketHandlers方法, 注册自定义的WebSocketHandler的实现类CustomWebSocketHandler, 并指定类对应的WebSocket问的ServerEndpoint为/myWs。
 * 通过注入
 * 通过@EnableWebSocket注解,启动spring-boot-starter-websocket的自动化配置。
 * @Author C_Y_J
 * @create 2022/7/7 14:33
 **/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private CustomWebSocketHandler customWebSocketHandler;

    @Autowired
    private CustomTextWebSocketHandler customTextWebSocketHandler;

    @Autowired
    private CustomWebSocketInterceptor customWebSocketInterceptor;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                .addHandler(customWebSocketHandler, "myWs3")
                .addHandler(customTextWebSocketHandler, "myWs2")

                .addInterceptors(customWebSocketInterceptor)
                .setAllowedOrigins("*");
    }

    /**
     * {@link com.websocket.java.websocket.controller.WsServerController}
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpoint() {
        return new ServerEndpointExporter();
    }
}

